<template>
  <div class="main">
      <div  class="top-title">
        <div class="top-pace">
          <a-row>
            <a-col :span="5">
                <h3><span>专业名称：</span>供电专业</h3>
            </a-col>
            <a-col :span="3">
                <h3><span>机构名称：</span></h3>
            </a-col>
            <a-col :span="4">
              <a-tree-select
                      v-model:value="value"
                      show-search
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                      allow-clear
                      tree-default-expand-all
                      :tree-data="powerTreeData"
                      @change="handleSelected(value)"
                  />
            </a-col>

            <a-col :span="3" :style="{marginLeft : 30+'px'}"><h3><span>绝缘工具名称：</span></h3></a-col>
            <a-col :span="4">
              <a-select
                  v-model:value="value1"
                  show-search
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  allow-clear
                  tree-default-expand-all
                  :options="teamTool"
              />
            </a-col>

            <a-col :span="4">
              <a-button @click="handleQueryClick(value,value1)" class="query-btn">查询</a-button>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="16">
            <div class="search">
              <a-tooltip>
              <template #title>prompt text</template>
              提醒：<span>{{ remindWorkshopName }} </span><span>{{ remindTeamName }}</span>班组编号为<span>{{ remindId }}</span>的<span>{{ remindName }}</span>还有<span>{{ remindDaysDiff }}</span>天到有效截止日期<span>{{ remindExpireDate }}</span>.
              </a-tooltip>
              <a-button @click="handleDetailClick()" class="btn">详情查看</a-button>
            </div>
          </a-col>
          <a-col :span="4">
            <a-button @click="handleBaseMaintainClick()" class="query">基础信息维护</a-button>
          </a-col>
          </a-row>
          <a-row>
            <a-col :span="16">
              <div class="scrap">
                <a-tooltip>
                <template #title>prompt text</template>
                提醒：<span>{{scrapValue.scrapWorkshop}}</span><span>{{scrapValue.scrapTeam}}</span>班组编号为<span>{{ scrapValue.scrapId }}</span>的<span>{{ scrapValue.scrapToolName }}</span> &ensp;<span>已报废</span>
                </a-tooltip>
                <a-button @click="handleScrapClick(value)" class="btn">报废信息查询</a-button>
              </div>
            </a-col>
            <a-col :span="4">
              <a-button @click="handleTrialMaintainClick()" class="query">试验信息维护</a-button>
            </a-col>
          </a-row>
        </div>
          <!-- <div class="export">
            <a-button @click="handleExportClick" id="export">导出</a-button>
          </div> -->
          <div class="export">
            <a-button id="import">导入 excel</a-button>
            <a-upload :before-upload="importFile" :show-file-list="false" accept=".xls,.xlsx,.csv">
              <a-button @click="handleExportClick" id="export">导出 excel</a-button>
            </a-upload>
          </div>
          <a-table :columns="columns" :data-source="data">
              <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex === 'operation'">
                      <button class="data-btn" @click="handleBasicInfoWrite(record)">基础信息填写</button>
                      <!-- <button class="data-btn" @click="handleTrialHistoryData">试验历史数据</button> -->
                      <button class="data-btn" @click="handleHisDataClick(record)">历史数据</button>
                  </template>
              </template>
              <template #expandedRowRender="{record}">
                <a-table :columns="innerColumns" :data-source="innerData[record.key]" :pagination="false" >
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'operation'">
                        <button class="data-btn" @click="handleTrialHistoryRecord(record)">试验历史记录</button>
                        <button class="data-btn" @click="handleTrialDataAdd(record)">试验数据填写</button>
                    </template>
                    <!-- <template v-if="column.dataIndex === 'id'">
                      <template v-if="record.id===''">
                        <a-input v-model:value="record.count" style="width: 80px"/>
                        <button class="data-btn" @click="handleSure">确定</button>
                      </template>
                    </template> -->
                  </template>
                </a-table>
                <a-button type="dashed" style="background-color: #169bd5;justify-items: center;color: white" @click="addDomain(record)">
                  <PlusOutlined />
                  增加具体内容
                </a-button>
              </template>
          </a-table>
      </div>
      <basicInfoWrite ref="showBasicInfoWrite" :showBasicInfoWriteId="showId" @load-data="loadData"></basicInfoWrite>
      <Detail ref="showDetail" :powerTreeData="powerTreeData" :dataDetail="dataDetail"></Detail>
      <trialHistoryData ref="showTrialHistoryData" :selectRecord2="selectRecord2" :historyData="historyData"></trialHistoryData>
      <ScrapInfoQueryModal ref="showWorthless" :powerTreeData="powerTreeData"></ScrapInfoQueryModal>
      <BaseInfoMaintainModal ref="showMaintain" :powerTreeData="powerTreeData"></BaseInfoMaintainModal>
      <TestInfoMaintainModal ref="showTestMaintain" :powerTreeData="powerTreeData"></TestInfoMaintainModal>
      <TestInfoWriteModal ref="showTestInfoWriteModal" :toolId="toolId" @load-data="loadData"></TestInfoWriteModal>
      <writeNumber ref="showWriteNumber" @load-data="loadData"></writeNumber>
      <HistoryModal ref="showHistoryModal" :selectRecord1="selectRecord1" :historyData="historyData"></HistoryModal>
  </div>
</template>

<script setup>
import { PlusOutlined } from '@ant-design/icons-vue'
import { ref,computed,unref,onMounted,watchEffect,reactive,watch} from 'vue'
import basicInfoWrite from '@/views/team2/powerModule/records/basicInfoWriteModal.vue'
import Detail from '@/views/team2/powerModule/records/Detail.vue'
import trialHistoryData from '@/views/team2/powerModule/records/HistoryDataModal.vue'
import ScrapInfoQueryModal from '@/views/team2/powerModule/records/ScrapInfoQueryModal.vue'
import BaseInfoMaintainModal from './BaseInfoMaintainModal.vue'
import TestInfoMaintainModal from './TestInfoMaintainModal.vue'
import request from '@/utils/request'
import TestInfoWriteModal from '@/views/team2/powerModule/records/TestInfoWriteModal.vue'
import writeNumber from './writeNumber.vue'
import HistoryModal from './HistoryModal.vue'
import { message } from 'ant-design-vue';
import { utils, writeFile, read } from 'xlsx';

const showId=ref()
const id = ref('1')
const toolName = ref('验电器')
const day = ref('20')
const date = ref('6月30日')

const scrapValue=reactive({
  scrapWorkshop:'',
  scrapTeam:'',
  scrapId:'',
  scrapToolName:''

})

const teamTool=ref([
{
 value: '验电器',
 label: '验电器',
 }, {
  value: '110kv验电器',
  label: '110kv验电器',
 }, {
  value: '27.5kv验电器',
  label: '27.5kv验电器',
 }, {
  value: '10kv验电器',
  label: '10kv验电器',
 }, {
  value: '打杂杆', 
   label: '打杂杆',
 }, {
  value: '令克棒',
  label: '令克棒',
 }, {
  value: '接地杆',
  label: '接地杆',
 }, {
  value: '绝缘手套',
  label: '绝缘手套',
 }, {
  value: '绝缘靴',
  label: '绝缘靴',
 }, {
  value: '打冰杆',
  label: '打冰杆',
 }, {
  value: '等电位杆',
   label: '等电位杆',
 }, {
  value: '绝缘测杆',
  label: '绝缘测杆',
 }, {
  value: '绝缘操作手柄',
  label: '绝缘操作手柄',
 },
])

const value = ref()
const value1=ref()

const selectRecord1 = ref()
const selectRecord2 = ref()
const historyData = ref([])

const showDetail = ref(null)
const showBasicInfoWrite = ref(null)
const showTrialHistoryData = ref(null)
const showWorthless = ref(null)
const showMaintain = ref(null)
const showTestMaintain = ref(null)
const showWriteNumber=ref(null)
const showHistoryModal=ref(null)
// 定义一个变量，传给detail模态框
const dataDetail = ref([])

// 设置几个参数用于页面中的提醒信息 分别是车间、班组、工具名、工具id、到期天数、到期日期
const remindWorkshopName = ref('')
const remindTeamName = ref('')
const remindName = ref('')
const remindId = ref()
const remindDaysDiff = ref()
const remindExpireDate = ref('')

// 定义一个变量，存储id传给testInfoWriteModal
const toolId = ref()
// 定义一个变量存储所选的行传给testInfoWriteModal
const selectedKeys=ref()

//定义表头
const columns = ref([{
title: '车间',
dataIndex: 'workShopName',
key: 'workShopName',
align:'center'
}, {
title: '班组',
dataIndex: 'teamName',
key: 'teamName',
align:'center'
// width: 80,
}, {
title: '编号',
dataIndex: 'number',
key: 'number',
align:'center'
// ellipsis: true,
}, {
title: '名称',
dataIndex: 'name',
key: 'name',
align:'center'
// ellipsis: true,
}, {
title: '规格、型号',
dataIndex: 'specification',
key: 'specification',
align:'center'
// ellipsis: true,
}, {
title: '试验日期',
dataIndex: 'testDate',
key: 'testDate',
align:'center'
// ellipsis: true,
}, {
title: '试验周期(具有效截止日期)',
dataIndex: 'expireDate',
key: 'expireDate',
width:100,
align:'center'

// ellipsis: true
}, {
title: '试验电压(kv)',
dataIndex: 'testVoltage',
key: 'testVoltage',
align:'center'
// ellipsis: true,
}, {
title: '试验人',
dataIndex: 'tester',
key: 'tester',
align:'center'
// ellipsis: true,
}, {
title: '审核人',
dataIndex: 'auditor',
key: 'auditor',
// ellipsis: true,
}, {
title: '保管人',
dataIndex: 'keeper',
key: 'keeper',
align:'center'
// ellipsis: true,
}, {
title: '试验结论',
dataIndex: 'operateConclusion',
key: 'operateConclusion',
align:'center'
// ellipsis: true,
}, {
title: '状态',
dataIndex: 'status',
key: 'status',
align:'center'
// ellipsis: true,
}, {
title: '投运日期',
dataIndex: 'operateDate',
key: 'operateDate',
align:'center'
// ellipsis: true,
}, {
title: '操作',
dataIndex: 'operation',
key: 'operation',
align:'center',
width:130
// ellipsis: true,
}])
const data = ref([]);

const showTestInfoWriteModal=ref(null)

const innerColumns=ref([{
  title:'编号',
  // dataIndex:'number',
  dataIndex:'id',
  key:'id',
  align:'center'
},
{
  title:'试验日期',
  // dataIndex:'test_date',
  dataIndex:'testDate',
  key:'testDate',
  align:'center'
},
{
  title:'有效截止日期',
  dataIndex:'expireDate',
  key:'expireDate',
  align:'center'
},
{
  title:'试验人',
  dataIndex:'tester',
  key:'tester',
  align:'center'
},
{
  title:'审核人',
  dataIndex:'auditor',
  key:'auditor',
  align:'center'
},
{
  title:'投运日期',
  dataIndex:'operateDate',
  key:'operateDate',
  align:'center'
},
{
  title:'试验结论',
  dataIndex:'operateConclusion',
  key:'operateConclusion',
  align:'center'
},
{
  title:'操作',
  dataIndex:'operation',
  key:'operation',
  align:'center'
},

])
const innerData=ref([])

const powerTreeData = ref([]);
// const toolValue=ref([])

const addDomain=(record)=>{
  // console.log(record)
  showWriteNumber.value.showModal(record)
}

//导出
// const handleExportClick=()=>{

  //导出
 const handleExportClick = async () => {
 const array = [['序号', '车间名称', '班组名称', '编号','工具名称', '规格型号', '试验日期', '试验人', '审核人', '保管人', '试验结论', '投运日期']];
 data.value.forEach((d, i) => {
    array.push([i + 1, d.workshopName, d.teamName, d.id, d.name, d.specification, d.testDate, d.tester, d.auditor, d.keeper, d.operateConclusion]);
 });
 const sheet = utils.aoa_to_sheet(array);
 // console.log(sheet)
 writeFile(
  {
   SheetNames: ['Sheet1'],
   Sheets: {
    Sheet1: sheet
   }
  },
  '记录统计.xlsx'
 );
};

// 导入
const importFile = ({ file }) => {
const reader = new FileReader();
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = read(data, {type: 'array'});
const sheetNames = workbook.SheetNames;
const worksheet = workbook.Sheets[sheetNames[0]];
// 解析成二维数组
const aoa = utils.sheet_to_json(worksheet, { header: 1 });
console.log(aoa);
};
reader.readAsArrayBuffer(file);
return false;
}

//加载工具
const handleSelected=async()=>{
  // teamTool.value=[]
  //   // console.log(orgId.value)
  //   const result =await request({
  //     url:'/api/quota/optionalTools',
  //     method:'get',
  //     params:{
  //       orgId:value
  //     }
  //   })
  //   console.log(result.data.data)
  //   for(var i=0;i<result.data.data.length;i++){
  //     var obj={
  //       value:result.data.data[i].name,
  //       label:result.data.data[i].name
  //     }
  //     teamTool.value.push(obj)
  //   }
    // console.log(teamTool.value)
}

//加载数据
const loadData = async () => {
  console.log(1111)
  const result = await request.get(`/recordstatistics/show`)
  // 从接口获取到数据渲染在表格中
  console.log(result)
  data.value = result.data.data
  // data.value={...result.data.data}
  // Object.assign(data.value,result.data.data)
  // console.log(data.value)

  // 给每条数据都加一个key实现可多选的功能
  for(let i=0;i<data.value.length;i++){
    data.value[i].key = i 
    if(data.value[i].status===0){
      data.value[i].status='正常'
    }else if(data.value[i].status===1){
      data.value[i].status='下架'
    }else if(data.value[i].status===2){
      data.value[i].status='报废'
    }
  }

  innerData.value=[]
  for(let i=0; i<data.value.length;i++){
    innerData.value.push(data.value[i].toolDetailList)
    //给子表中的数据加上唯一标识key
    for(let j=0; j<innerData.value[i].length;j++){
      innerData.value[i][j].key=innerData.value[i][j].id
    }
  }

  console.log(innerData.value)
}
// watch(data.value,()=>{
//   console.log(222222)
//   loadData()
// })
// watchEffect(()=>{
// for(let i=0; i<data.value.length;i++){
//     innerData.value.push(data.value[i].toolDetailList)
//     //给子表中的数据加上唯一标识key
//     for(let j=0; j<innerData.value[i].length;j++){
//       innerData.value[i][j].key=j
//     }
//   }
// })

watchEffect(()=>{
  if(value.value===undefined && value1.value===undefined){
    loadData()
  }
})

onMounted(async() =>{
  //机构名称
  const result = await request({
    url:'/sys/orgTree',
    method:'get',
    params:{
      speciality:1
    }
  })
powerTreeData.value=result.data.data[0].children[0].children

// 获取详情查看中的数据
 const remindResult = await request({
    url:'/tools/reminder',
    method:'get',
    params:{
    speciality:1
    }
  })
  console.log(remindResult)
  remindWorkshopName.value = remindResult.data[0].workshopName
  remindTeamName.value = remindResult.data[0].teamName
  remindName.value = remindResult.data[0].name
  remindId.value = remindResult.data[0].id
  remindDaysDiff.value = remindResult.data[0].daysDiff
  remindExpireDate.value = remindResult.data[0].expireDate
 // console.log(result.data);
 dataDetail.value = remindResult.data

//加载所有报废信息
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const res=await request({
  url:'/scrap/selectall',
  method:'get'
})
scrapValue.scrapWorkshop=res.data.data[0].workshop
scrapValue.scrapTeam=res.data.data[0].team
scrapValue.scrapId=res.data.data[0].number
scrapValue.scrapToolName=res.data.data[0].name

loadData()
  
// console.log(powerTreeData.value)
})

const handleChange = value => {
console.log(`selected ${value}`);
};

const filterOption = (input, option) => {
return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

//查询按钮
const handleQueryClick = async(value,value1) =>{
  // console.log(value);
  if(!value & !value1){
    message.info('请选择机构和工具');
  }
  else if(!value){
    message.info('请选择机构');
  }
  else if(!value1){
    message.info('请选择工具');
  }
  else{
    // 根据id获取名称
  const teamValue=ref([])
  const res = await request.get(`/sys/getSubOrg`)
  teamValue.value=res.data.data

  const orgName=ref('')
  for(var i=0;i < teamValue.value.length;i++){
  if(value===teamValue.value[i].orgId){
  orgName.value=teamValue.value[i].orgName
  }
 }
    const result = await request({
      url:'/recordstatistics/show',
      method:'get',
      params:{
        orgName:orgName.value,
        toolName:value1

        // orgName:'商丘接触网维修工区',
        // toolName:'验电器'
      }
    })
    console.log(result)
    data.value = result.data.data
  }
  
}
//详情查看
//详情查看
const handleDetailClick = () => {
 showDetail.value.showModal()
} 
//基础信息维护
const handleBaseMaintainClick = () => {
showMaintain.value.showModal()
}
//报废信息查询
const handleScrapClick = () =>{
showWorthless.value.showModal()
}
// 试验信息维护
const handleTrialMaintainClick = () => {
showTestMaintain.value.showModal()
}
// 基础信息填写
const handleBasicInfoWrite=(record)=>{
showId.value=record.id
// console.log(record);
// console.log(showId.value)
showBasicInfoWrite.value.showModal()
}
// 试验历史数据
// const handleTrialHistoryData=()=>{
// showTrialHistoryData.value.showModal()
// }
//历史数据
const handleHisDataClick = async(record) =>{
  console.log(1111);
  selectRecord1.value = record
  console.log(selectRecord1.value);
  //  获取历史数据
  const result = await request({
      url:'/tools/showkeeperlog',
      method:'get',
      params:{
        tid:record.id
        // toolid:selectRecord.value.id.toString()
      }
    })
    console.log(result);
    historyData.value = result.data.data.data
    console.log(historyData.value);
    showHistoryModal.value.showModal()
}
// 试验历史记录
const handleTrialHistoryRecord = async (record)=>{
  selectRecord2.value = record
  const id = record.id.slice(0,1)
  const result = await request({
  url:'/scrap/historylist',
  method:'get',
  params:{
  toolid:Number(id)
  }
  })
  // console.log(result.data.data);
  historyData.value = result.data.data
  selectedRowKeys.value = []
  showTrialHistoryData.value.showModal()
}

// 试验信息填写
const handleTrialDataAdd=(record)=>{
 toolId.value = record.id
// console.log(toolId.value);
 selectedRowKeys.value = []
 showTestInfoWriteModal.value.showModal()
 // showAddInfo.value.showModal()
}

//子表
const selectedRowKeys=ref([])
const onSelectChange = changableRowKeys => {
  console.log('selectedRowKeys changed: ', changableRowKeys);
  selectedRowKeys.value = changableRowKeys;
};
const rowSelection = computed(()=>{
// console.log(selectedRowKeys);
return {
  selectedRowKeys: unref(selectedRowKeys),
  onChange: onSelectChange,
}

})
</script>

<style lang="less" scoped>
.main{
    // padding: 20px ;
}
.top-title{
  margin: 20px 0 20px 0;
}
.top-pace{
  margin-left: 20px;
}
h3{
    display: inline-block;
}
span{
  font-weight: 700;
}
.search{
  height: 50px;
  width: 800px;
  background-color: rgb(242, 253, 224);
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.scrap{
  height: 50px;
  width: 800px;
  background-color: rgb(215,172,255);
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.query{
    background-color: #169bd5;
    border: 1px solid #ccc;
    border-radius: 6px;
    font-size: 15px;
    color: white;
    height: 38px;
    width: 110px;
    text-align:center;
    padding: 4px;
}

.query-btn{
  background-color: #169bd5;
    border: 1px solid #ccc;
    border-radius: 6px;
    font-size: 15px;
    color: white;
    height: 38px;
    width: 60px;
    text-align:center;
    padding: 4px;
    margin-left: 20px;
}

.data-btn{
  background-color: #169bd5;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 14px;
  color: white;
  width: 60px;
}
.btn{
      background-color: #169bd5;
      border: 1px solid #ccc;
      border-radius: 6px;
      font-size: 15px;
      color: white;
      height: 38px;
      width: 100px;
      padding: 0;
}
/deep/ .ant-table-tbody > tr > td {
  padding: 10px 5px!important;
  text-align: center;
}
.export{
  padding: 10px 0 10px 0;
  margin-left: 20px;
}
#export,#import{
    background-color: #169bd5;
    border: 1px solid #ccc;
    border-radius: 6px;
    font-size: 15px;
    color: white;
    height: 38px;
    width: 80px;
    text-align:center;
    padding: 4px;
}
</style>

